<?php

namespace App\Common;


use App\Models\AlipayHbReturn;
use App\Models\Merchant;
use App\Models\MerchantWalletDetail;
use App\Models\Order;
use App\Models\Store;
use App\Models\User;
use App\Models\UserWalletDetail;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class UserHbfqGetMoney
{

    public $store_id;//门店
    public $out_trade_no;//订单号
    public $order_total_amount;//订单金额
    public $user_id;//直属推广员ID
    public $ways_type;//通道类型
    public $store_ways_type_rate;//门店通道类型费率
    public $source_type;//返佣类型
    public $source_desc;//返佣类型说明
    public $config_id;//返佣类型说明
    public $merchant_id;//返佣类型说明
    public $merchant_name;//返佣类型说明
    public $store_name;//返佣类型说明


    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($data)
    {


        $this->user_id = $data['user_id'];
        $this->store_id = $data['store_id'];
        $this->out_trade_no = $data['out_trade_no'];
        $this->ways_type = $data['ways_type'];
        $this->order_total_amount = $data['order_total_amount'];
        $this->store_ways_type_rate = $data['store_ways_type_rate'];
        $this->source_type = $data['source_type'];
        $this->source_desc = $data['source_desc'];
        $this->config_id = $data['config_id'];
        $this->num = $data['num'];
        $this->merchant_id = $data['merchant_id'];
        $this->merchant_name = $data['merchant_name'];
        $this->store_name = $data['store_name'];


    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function insert()
    {
        try {

            $now_user_id = $this->user_id;//商户直接归属的代理商id
            $user = User::join('alipay_user_hbrates', 'users.id', 'alipay_user_hbrates.user_id')
                ->where('users.id', $now_user_id)
                ->where('alipay_user_hbrates.num', $this->num)
                ->select('alipay_user_hbrates.rate', 'users.pid', 'users.level', 'users.name', 'users.phone')
                ->first();

            if ($user) {
                $day = date('Ymd', time());
                $pid_user_id = $user->pid;
                $level = $user->level;//商户直接归属的代理商等级

                //分期的费率
                $user_rate = $user->rate;//设置成本
                $end_user_rate = $user_rate;//最终成本


                //查询是否有对商户返还
                $AlipayHbReturn = AlipayHbReturn::where('store_id', $this->store_id)
                    ->where('num', $this->num)
                    ->select('rate', 'r_type')
                    ->first();

                if ($AlipayHbReturn) {
                    $money = ($AlipayHbReturn->rate * $this->order_total_amount) / 100;

                    if ($money > 0 && (($AlipayHbReturn->rate + $end_user_rate) < $this->store_ways_type_rate)) {
                        $end_user_rate = $user_rate + $AlipayHbReturn->rate;

                        $MerchantWalletDetail = [
                            'config_id' => $this->config_id,
                            'store_id' => $this->store_id,
                            'merchant_id' => $this->merchant_id,
                            'merchant_name' => $this->merchant_name,
                            'store_name' => $this->store_name,
                            'phone' => '',
                            'money' => $money,
                            'out_trade_no' => $this->out_trade_no,
                            'trade_no' => $this->out_trade_no,
                            'source_type' => $this->source_type,
                            'source_desc' => $this->source_desc,
                        ];


                        //返给门店
                        if ($AlipayHbReturn->r_type == "1") {
                            $Store = Store::where('store_id', $this->store_id)
                                ->select('merchant_id')
                                ->first();
                            if ($Store) {
                                $MerchantWalletDetail['merchant_id'] = $Store->merchant_id;
                            }
                        }

                        //入库

                        $merchant = Merchant::where('id', $MerchantWalletDetail['merchant_id'])
                            ->select('phone', 'name')
                            ->first();

                        if ($merchant) {
                            $MerchantWalletDetail['phone'] = $merchant->phone;
                            $MerchantWalletDetail['merchant_name'] = $merchant->name;
                            self::insert_MerchantWalletDetail($MerchantWalletDetail, $day);
                        }
                    }
                }


                if ($this->store_ways_type_rate < $user_rate) {
                    return "";
                }


                $name = $user->name;
                $phone = $user->phone;

                $money = $this->order_total_amount * ($this->store_ways_type_rate - $end_user_rate);//直属代理商
                $money = $money / 100;
                $money = number_format($money, 4, '.', '');
                $store_id = $this->store_id;
                $config_id = $this->config_id;
                $out_trade_no = $this->out_trade_no;
                $source_type = $this->source_type;
                $source_desc = $this->source_desc;


                $user_detail = [
                    'store_id' => $store_id,
                    'config_id' => $config_id,
                    'user_id' => $now_user_id,
                    'user_name' => $name,
                    'phone' => $phone,
                    'money' => $money,
                    'out_trade_no' => $out_trade_no,
                    'trade_no' => $out_trade_no,
                    'source_type' => $source_type,
                    'source_desc' => $source_desc,
                ];

                //直属入库

                if ($money > 0) {
                    self::insert_UserWalletDetail($user_detail, $day);
                }


                $sub_user_rate = $user_rate;

                for ($x = $level; $x >= 0; $x--) {

                    try {
                        $user = User::join('alipay_user_hbrates', 'users.id', 'alipay_user_hbrates.user_id')
                            ->where('users.id', $pid_user_id)
                            ->where('alipay_user_hbrates.num', $this->num)
                            ->select('alipay_user_hbrates.rate', 'users.id', 'users.pid', 'users.level', 'users.name', 'users.phone')
                            ->first();
                        if (!$user) {
                            continue;
                        }
                        //直到循环到顶级
                        if ($user->pid == 0) {
                            break;
                        }


                        $pid_user_id = $user->pid;//上级ID

                        //支付宝微信扫码费率
                        $user_rate = $user->rate;


                        $name = $user->name;
                        $phone = $user->phone;
                        $now_user_id = $user->id;
                        $money = $this->order_total_amount * ($sub_user_rate - $user_rate);//直属代理商
                        $money = $money / 100;
                        $money = number_format($money, 4, '.', '');

                        $user_detail = [
                            'store_id' => $store_id,
                            'config_id' => $config_id,
                            'user_id' => $now_user_id,
                            'user_name' => $name,
                            'phone' => $phone,
                            'money' => $money,
                            'out_trade_no' => $out_trade_no,
                            'trade_no' => $out_trade_no,
                            'source_type' => $source_type,
                            'source_desc' => $source_desc,
                        ];

                        if ($money > 0) {
                            self::insert_UserWalletDetail($user_detail, $day);
                        }
                        $sub_user_rate = $user_rate;
                    } catch (\Exception $exception) {
                        \Illuminate\Support\Facades\Log::info($exception);
                        continue;
                    }

                }

            }


        } catch (\Exception $exception) {
            \Illuminate\Support\Facades\Log::info($exception);
        }
    }


    //公共进库
    public static function insert_UserWalletDetail($UserWalletDetail, $day)
    {
        try {

            //如果存在base
            if (Schema::hasTable('user_wallet_details_base')) {
                //后面可以不进这个数据库
                $table = 'user_wallet_details_' . $day;
                //判断是否有表
                if (!Schema::hasTable($table)) {
                    //无表
                    DB::update('create table ' . $table . ' like 	user_wallet_details_base');
                }
                $UserWalletDetail['created_at'] = date('Y-m-d H:i:s', time());
                $UserWalletDetail['updated_at'] = date('Y-m-d H:i:s', time());
                $a = DB::table($table)->insert($UserWalletDetail);
            } else {

                UserWalletDetail::create($UserWalletDetail);

            }


        } catch (\Exception $exception) {
            \Illuminate\Support\Facades\Log::info('user_wallet_details_base');
            \Illuminate\Support\Facades\Log::info($exception);
        }
    }


    //公共进库
    public static function insert_MerchantWalletDetail($MerchantWalletDetail, $day)
    {
        try {

            //如果存在base
            if (Schema::hasTable('merchant_wallet_details_base')) {
                //后面可以不进这个数据库
                $table = 'merchant_wallet_details_' . $day;
                //判断是否有表
                if (!Schema::hasTable($table)) {
                    //无表
                    DB::update('create table ' . $table . ' like merchant_wallet_details_base');
                }
                $MerchantWalletDetail['created_at'] = date('Y-m-d H:i:s', time());
                $MerchantWalletDetail['updated_at'] = date('Y-m-d H:i:s', time());
                DB::table($table)->insert($MerchantWalletDetail);

            } else {

                MerchantWalletDetail::create($MerchantWalletDetail);

            }


        } catch (\Exception $exception) {
            \Illuminate\Support\Facades\Log::info('merchant_wallet_details_base');
            \Illuminate\Support\Facades\Log::info($exception);
        }
    }


}
